import numpy as np
import matplotlib.pyplot as plt

# 生成虚拟数据
np.random.seed(0)
x = np.linspace(0, 10, 10)  # 原始数据x点
y = np.sin(x) + np.random.normal(0, 0.1, len(x))  # 添加一些噪声的原始y值

# 牛顿插值算法实现
def newton_interpolation(x, y, x_new):
    n = len(x)
    divided_diff = np.zeros((n, n))
    divided_diff[:, 0] = y

    for j in range(1, n):
        for i in range(n - j):
            divided_diff[i, j] = (divided_diff[i + 1, j - 1] - divided_diff[i, j - 1]) / (x[i + j] - x[i])

    # 计算插值值
    y_new = np.zeros_like(x_new)
    for i in range(len(x_new)):
        term = 1
        y_new[i] = divided_diff[0, 0]
        for j in range(1, n):
            term *= (x_new[i] - x[j - 1])
            y_new[i] += divided_diff[0, j] * term

    return y_new

# 插值计算
x_new = np.linspace(0, 10, 100)  # 新的x点
y_interp = newton_interpolation(x, y, x_new)  # 牛顿插值获得的y值

# 真实的sin(x)曲线
y_true = np.sin(x_new)

# 误差计算
error = y_true - y_interp

# 绘图
plt.figure(figsize=(12, 8))

# 图1：原始数据点与插值曲线
plt.subplot(2, 1, 1)
plt.scatter(x, y, color='red', label='Original Data Points')
plt.plot(x_new, y_interp, color='blue', label='Newton Interpolation Curve')
plt.plot(x_new, y_true, color='green', linestyle='--', label='True sin(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Newton Interpolation vs. True Function')
plt.legend()
plt.grid()

# 图2：误差分析图
plt.subplot(2, 1, 2)
plt.plot(x_new, error, color='purple', label='Interpolation Error')
plt.xlabel('x')
plt.ylabel('Error')
plt.title('Interpolation Error Analysis')
plt.legend()
plt.grid()

# 展示图形
plt.tight_layout()
plt.show()
